#coding=utf8
import sys
import os

from google.protobuf.descriptor import EnumDescriptor

def write_import(f,pack,l):
	f.write('from %s import '%pack)
	f.write(l[0])
	for i in l[1:]:
		f.write(',%s'%i)
	f.write('\n')

def gen():
	CODE_PATH = 'proto/code/'
	CODE_PACK = 'proto.code'
	PROTO_PATH = 'proto/player/'
	PROTO_PACK = 'proto.player'

	PROTO_MOD = 'player'
	CODE_MOD = 'code'

	sys.path.append(CODE_PATH)
	sys.path.append(PROTO_PATH)

	# gen all protocode enum
	enum_set = set()
	mod_enum_dict = {}
	l = os.listdir(CODE_PATH)
	for i in l:
		if not os.path.isdir(CODE_PATH+i) and i.endswith('pb2.py'):
			modname = i[:i.find('.py')]
			#print modname
			mod_enum_dict[modname] = []
			mod = __import__(modname)
			attrname_list = dir(mod)
			for attrname in attrname_list:
				attr = getattr(mod,attrname)
				if isinstance(attr,EnumDescriptor):
					for value in attr.values:
						enum_set.add(value.name)
						mod_enum_dict[modname].append(value.name)

	f = open(CODE_PATH+CODE_MOD+'.py','w')
	f.write('#coding=utf8\n\n')
	for k,v in mod_enum_dict.iteritems():
		write_import(f,k,v)
	f.close()

	proto_list = []
	mod_proto_dict = {}
	l = os.listdir(PROTO_PATH)
	for i in l:
		if not os.path.isdir(PROTO_PATH+i) and i.endswith('pb2.py'):
			modname = i[:i.find('.py')]
			#print modname
			mod_proto_dict[modname] = []
			mod = __import__(modname)
			for name in mod.DESCRIPTOR.message_types_by_name.iterkeys():
				proto_list.append(name)
				mod_proto_dict[modname].append(name)

	f = open(PROTO_PATH+PROTO_MOD+'.py','w')
	f.write('#coding=utf8\n\n')
	for k,v in mod_proto_dict.iteritems():
		write_import(f,k,v)
	f.close()

	enum2proto_list = []
	for i in proto_list:
		enum_name = i.upper()
		if enum_name in enum_set:
			enum2proto_list.append((enum_name,i))
		else:
			print 'enum not exist: %s'%enum_name

	print enum2proto_list

	f = open('cmd2proto.py','w')
	f.write('#coding=utf8\n\n')
	f.write('#this file is auto generated by gen_cmd2proto.py, do not modify it!\n\n')
	f.write('from %s import %s\n'%(CODE_PACK,CODE_MOD))
	f.write('from %s import %s\n'%(PROTO_PACK,PROTO_MOD))
	f.write('\n')
	f.write('proto_dict = {\n')
	for c,p in enum2proto_list:
		f.write('\t%s.%s:%s.%s,\n'%(CODE_MOD,c,PROTO_MOD,p))
	f.write('\t}')
	f.close()

	return

if __name__ == '__main__':
	gen()
	print 'generate complete'

